package com.servlet;

import com.bean.Student;
import com.google.gson.Gson;
import com.service.StudentService;
import com.service.impl.StudentServiceImpl;
import com.utils.Page;
import com.utils.WebUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

import static com.utils.Page.PAGE_SIZE;

@WebServlet(name = "StudentServlet", urlPatterns = "/StudentServlet.do")
public class StudentServlet extends BaseServlet {
    StudentService studentService = new StudentServiceImpl();

    protected void page(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int pageNo = WebUtils.parseInt(request.getParameter("pageNo"), 1);
        int pageSize = WebUtils.parseInt(request.getParameter("pageSize"), PAGE_SIZE);
        String content = request.getParameter("content");
        Page<Student> page = studentService.page(pageNo, pageSize, content);
        Map map = new LinkedHashMap();
        map.put("code", 0);
        map.put("msg", "");
        map.put("count", page.getPageTotalCount());
        map.put("data", page.getItems());
        response.getWriter().write(WebUtils.parseJson(map));
    }

    protected void add(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Student student = new Student();
        WebUtils.copyParamToBean(request.getParameterMap(), student);
        student.setId(null);
        int tip = studentService.insert(student);
        String jsonStr = String.valueOf(tip);
        response.getWriter().write(jsonStr);
    }

    protected void del(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        int id = Integer.parseInt(request.getParameter("id"));
        int tip = studentService.deleteById(id);
        String jsonStr = String.valueOf(tip);
        response.getWriter().write(jsonStr);
    }

    protected void update(HttpServletRequest request, HttpServletResponse response) throws IOException {
        Student student = new Student();
        WebUtils.copyParamToBean(request.getParameterMap(), student);
        if (student.getPassword().equals("")) {
            student.setPassword(null);
        }
        int tip = studentService.updeteInfo(student);
        String jsonStr = String.valueOf(tip);
        response.getWriter().write(jsonStr);
    }
}
